package cn.lixin.order.service.impl;

import cn.lixin.basic.service.impl.BaseServiceImpl;
import cn.lixin.basic.utils.CodeGenerateUtils;
import cn.lixin.basic.utils.PageList;
import cn.lixin.order.contain.OrderConstants;
import cn.lixin.order.domain.AdoptOrder;
import cn.lixin.order.domain.OrderAddress;
import cn.lixin.order.mapper.AdoptOrderMapper;
import cn.lixin.order.mapper.OrderAddressMapper;
import cn.lixin.order.query.AdoptOrderQuery;
import cn.lixin.order.service.IAdoptOrderService;
import cn.lixin.org.domain.Employee;
import cn.lixin.org.mapper.EmployeeMapper;
import cn.lixin.pay.constants.PayConstants;
import cn.lixin.pay.domain.PayBill;
import cn.lixin.pay.mapper.PayBillMapper;
import cn.lixin.pay.service.IPayBillService;
import cn.lixin.pet.domain.Pet;
import cn.lixin.pet.mapper.PetMapper;
import cn.lixin.user.domain.Logininfo;
import cn.lixin.user.domain.User;
import cn.lixin.user.domain.UserAddress;
import cn.lixin.user.mapper.UserAddressMapper;
import cn.lixin.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

@Service
public class AdoptOrderServiceImpl extends BaseServiceImpl<AdoptOrder> implements IAdoptOrderService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private AdoptOrderMapper adoptOrderMapper;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PayBillMapper payBillMapper;
    @Autowired
    private IPayBillService payBillService;


    /**
     * 1.校验参数
     * 2.修改宠物状态 下架时间 绑定用户
     * 3. 创建宠物领养订单
     * 4. 支付订单
     * 5. 超时
     * @param params
     * @param logininfo
     * @return
     */
    @Override
    @Transactional
    public String submit(Map<String, Object> params, Logininfo logininfo) {
        /*
            校验
        */
        Integer serviceMethod = Integer.valueOf(params.get("service_method").toString()); // 配送方式
        Long  addressId = Long.valueOf(params.get("address_id").toString()); // 配送地址序号
        Long payMethod = Long.valueOf(params.get("pay_method").toString()); // 支付方式
        Long petId = Long.valueOf(params.get("pet_id").toString()); // 宠物的Id
/*        if (!StringUtils.isEmpty(serviceMethod) || !StringUtils.isEmpty(addressId)
                || !StringUtils.isEmpty(payMethod) || !StringUtils.isEmpty(petId)) {*/
            /*
            修改宠物状态 下架时间 绑定用户
            */
            Pet pet = petMapper.loadById(petId);
            pet.setState(0);
            pet.setOffsaletime(new Date());
            User user = userMapper.loadByLogininfoId(logininfo.getId());
            pet.setUser_id(user.getId());
            petMapper.update(pet);
             /*
            创建宠物领养订单
             */
            // 先创建订单
            AdoptOrder order = initAdoptOrder(pet, user);
            // 这里可以设置paySn、后面支付单就可以直接使用
            order.setPaySn(CodeGenerateUtils.generateUnionPaySn());
            adoptOrderMapper.save(order);
            // 再生成地址表的（不可被用户修改的当时下单的地址）
            UserAddress userAddress = userAddressMapper.loadById(addressId); // 根据上面的addressId获取
            OrderAddress orderAddress = initOrderAddress(order, userAddress);
            orderAddressMapper.save(orderAddress);
            System.out.println("虽然没有支付，金额："+order.getPrice());
            /*
            支付单
             */
            PayBill bill = initPayBill(payMethod, user, order);
            payBillMapper.save(bill);
            //统一支付接口 设计思想：别的方法让它的模块自己做
            return payBillService.pay(bill);

        /*}
        return null;*/
    }

    private PayBill initPayBill(Long payMethod, User user, AdoptOrder order) {
        PayBill bill = new PayBill();
        bill.setDigest(order.getDigest());
        bill.setMoney(order.getPrice());
        bill.setUnionPaySn(order.getPaySn()); //唯一订单标识，order已设置
        bill.setState(0);// 待支付
        bill.setLastPayTime(new Date(System.currentTimeMillis() + OrderConstants.LAST_PAY_TIME));
        bill.setPayChannel(payMethod);
        bill.setBusinessType(PayConstants.BUSINESS_TYPE_ADOPT); // 业务类型-领养
        bill.setBusinessKey(order.getId());// 用sn或者id都可以，但是后面需要用
        bill.setUser_id(order.getUser_id());
        bill.setShop_id(order.getShop_id());
        bill.setNickName(user.getUsername());
        // 设计思想：别的方法让它的模块自己做
        return bill;
    }

    @Override
    public PageList<AdoptOrder> admin(AdoptOrderQuery query, Logininfo currentLoginInfo) {
        Employee employee = employeeMapper.loadBylogininfoId(currentLoginInfo.getId());
        if (employee!=null){
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public PageList<AdoptOrder> user(AdoptOrderQuery query, Logininfo currentLoginInfo) {
        User user = userMapper.loadByLogininfoId(currentLoginInfo.getId());
        if (user!=null){
            query.setUserId(user.getId());
        }
        return null;
    }

    /**
     * 定时器执行任务-超时删除订单
     *
     * @param orderId
     */
    @Override
    public void deleteByQuartz(Long orderId) {
        AdoptOrder adoptOrder = adoptOrderMapper.loadById(orderId);
        if(adoptOrder.getState() ==0){// 未支付订单才可以删除，避免bug
            adoptOrder.setState(-1);
            // 这里直接上架宠物
            Long pet_id = adoptOrder.getPet_id();
            Pet cancelPet = petMapper.loadById(pet_id);
            cancelPet.setState(1);// 上架
            petMapper.update(cancelPet);
            adoptOrderMapper.update(adoptOrder);
            System.out.println("quartz 触发直接取消订单："+orderId);
        }
    }


    private OrderAddress initOrderAddress(AdoptOrder order, UserAddress userAddress) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress,orderAddress);
        orderAddress.setOrderSn(order.getOrderSn());
        orderAddress.setOrder_id(order.getId());
        return orderAddress;
    }

    private AdoptOrder initAdoptOrder(Pet pet, User user) {
        AdoptOrder order = new AdoptOrder();
        order.setDigest("[摘要]对-"+ pet.getName()+"-收购订单！");
        order.setState(0);//待支付
        order.setPrice(pet.getCostprice());
        String orderSn = CodeGenerateUtils.generateOrderSn(user.getId());
        order.setOrderSn(orderSn);
        order.setPet_id(pet.getId());
        order.setUser_id(user.getId());
        order.setShop_id(pet.getShop_id());
        order.setLastPayTime(new Date(System.currentTimeMillis() + OrderConstants.LAST_PAY_TIME));//支付超时自动取消
        return order;
    }
}
